<template>
    <div>
<!--      面包屑导航区域-->
      <Breadcrumb></Breadcrumb>
<!--      卡片视图-->
      <el-card>
        <el-row :gutter="20">
          <el-col :span="8">
            <!--        搜索与添加区域-->
            <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @click="getUserList">
              <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="addUserVisible=true">添加用户</el-button>
          </el-col>
        </el-row>
<!--        表格区-->
        <el-table
            :data="userList"
            style="width: 100%" border stripe>
          <el-table-column label="#" type="index" width="32px"></el-table-column>
          <el-table-column
              prop="username"
              label="姓名"
              width="100">
          </el-table-column>
          <el-table-column
              prop="email"
              width="150"
              label="邮箱">
          </el-table-column>
          <el-table-column
              prop="mobile"
              label="电话"
              width="150">
          </el-table-column>
          <el-table-column
              prop="role_name"
              label="角色"
              width="120">
          </el-table-column>
          <el-table-column
              prop="mg_state"
              label="状态"
              width="100">
            <template slot-scope="scope" >
              <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column
              label="操作"
              >
            <template slot-scope="scope" >
<!--              修改-->
              <el-tooltip class="item" effect="dark" content="修改" placement="top" :enterable="false">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"/>
              </el-tooltip>
              <!--              删除-->
              <el-tooltip class="item" effect="dark" content="删除" placement="top" :enterable="false">
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)"/>
              </el-tooltip>
              <!--              分配-->
              <el-tooltip class="item" effect="dark" content="分配" placement="top" :enterable="false">
                <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRoleDialog(scope.row)"/>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
<!--        分页区域-->
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="queryInfo.pagenum"
            :page-sizes="[1, 2, 5, 10]"
            :page-size="queryInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
      </el-card>
<!--      添加用户对话框-->
      <el-dialog
          title="添加用户"
          :visible.sync="addUserVisible"
          width="40%"
         @close="addDialogClosed" >
        <el-form ref="form" :model="addForm" label-width="80px" :rules="addFormRules">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addUserVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>


<!--      修改用户对话框-->
      <el-dialog
          title="修改用户"
          :visible.sync="editUserVisible"
          width="40%" >
        <el-form ref="editForm" :model="editForm" label-width="80px" :rules="editFormRules">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editUserVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUser">确 定</el-button>
        </span>
      </el-dialog>
      <!--      分配角色-->

      <el-dialog
          title="分配角色"
          :visible.sync="setRoleVisible"
          width="40%"  @close="setRoleClose">
        <div>
          <p>当前的用户:{{userInfo.username}}</p>
          <p>当前的角色:{{userInfo.role_name}}</p>
         <p>分配新角色:
           <el-select v-model="selectRoleId" placeholder="请选择">
            <el-option
                v-for="item in rolesList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id">
            </el-option>
          </el-select>
         </p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRoleVisible = false">取 消</el-button>
          <el-button type="primary" @click="setRole">确 定</el-button>
        </span>
      </el-dialog>
    </div>
</template>

<script>

import Breadcrumb from "@/components/Breadcrumb";

export default {
  name: "User",
  components:{
    Breadcrumb
  },
  data(){
    var checkEmail=(rule,value,cb)=>{
      const regEmail= /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
      if (regEmail.test(value)){
        return cb();
      }
      cb(new Error("请输入合法的邮箱"))
    }
    var checkMobile=(rule,value,cb)=>{
      const regMobile= /^(13[0-9]|14[5-9]|15[0-3,5-9]|16[6]|17[0-8]|18[0-9]|19[0-3,5-9])\d{8}$/;
      if (regMobile.test(value)){
        return cb();
      }
      cb(new Error("请输入合法的手机号"))
    }
    return{
      queryInfo:{
        query:'',
        pagenum:1,
        pagesize:2
      },
      userList:[],
      total:0,
      addUserVisible:false,
      addForm:{
        username:'',
        password: '',
        email:'',
        mobile: '',
      },
      addFormRules:{
        username: [
          { required:true ,message:"请输入用户名", trigger:"blur"},
          { min:3,max:10,message: "长度在3到10个字符",trigger: "blur"}
        ],
        password: [
          { required:true ,message:"请输入密码", trigger:"blur"},
          { min:6,max:15,message: "长度在6到15个字符",trigger: "blur"}
        ],
        email: [
          { required:true ,message:"请输入邮箱", trigger:"blur"},
          { validator:checkEmail,trigger: "blur"}
        ],
        mobile: [
          { required:true ,message:"请输入手机号", trigger:"blur"},
          { validator:checkMobile,trigger: "blur"}
        ]

      },
      editUserVisible:false,
      editForm:{},
      editFormRules:{
        email: [
          { required:true ,message:"请输入邮箱", trigger:"blur"},
          { validator:checkEmail,trigger: "blur"}
        ],
        mobile: [
          { required:true ,message:"请输入手机号", trigger:"blur"},
          { validator:checkMobile,trigger: "blur"}
        ]
      },
      setRoleVisible:false,
      userInfo:{},
      rolesList:[],
      selectRoleId:''

    }
  },
  created() {
      this.getUserList()
  },
  methods:{
    //得到用户列表
    async getUserList(){
      try {
        const {data:res} = await this.axios.get('users',{
          params:this.queryInfo
        });
        if (res.meta.status!==200){
          return this.$message.error(res.meta.msg)
        }
        this.userList=res.data.users;
        this.total=res.data.total

      }catch (e){
        this.$message.error("服务器出错请联系管理员")
      }
    },
    //改变pagesize
    handleSizeChange(newsize){
      this.queryInfo.pagesize=newsize;
      this.getUserList()
    },
    //改变pagenum
    handleCurrentChange(newNum){
      this.queryInfo.pagenum=newNum;
      this.getUserList()
    },
    //监听Switch开关状态
    async userStateChange(userinfo){
      try {
        const {data:res} = await this.axios.put(`users/${userinfo.id}/state/${userinfo.mg_state}`);
        if (res.meta.status!==200){
          return this.$message.error(res.meta.msg)
        }
      }catch (e){
        this.$message.error("服务器出错请联系管理员")
      }
    },
    //关闭添加对话框重置form
    addDialogClosed(){
        this.$refs.form.resetFields();
    },
    //发送请求添加用户
    addUser(){
      this.$refs.form.validate(async valid => {
        if (!valid) {
          return;
        }
        try {
          const {data: res} = await this.axios.post('users',this.addForm);
          if (res.meta.status !== 201) {
            return this.$message.error(res.meta.msg)
          }
          this.addUserVisible=false;
          this.getUserList()
          this.$message.success(res.meta.msg)
        } catch (e) {
          this.$message.error("服务器出错请联系管理员")
        }
      })
    },
    //展示修改对话框
    async showEditDialog(id) {
      this.editUserVisible = true
      try {
        const {data: res} = await this.axios.get(`users/${id}`);
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.editForm=res.data
      } catch (e) {
        this.$message.error("服务器出错请联系管理员")
      }
    },
    //发送请求修改用户
    editUser(){
      this.$refs.editForm.validate(async valid => {
        if (!valid) {
          return;
        }
        try {
          const {data: res} = await this.axios.put('users/'+this.editForm.id, {email:this.editForm.email,mobile:this.editForm.mobile});
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }
          this.editUserVisible=false;
          this.getUserList();
          this.$message.success(res.meta.msg)

        } catch (e) {
          this.$message.error("服务器出错请联系管理员")
        }
      })
    },
    // 删除用户
    removeUserById(id){
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const {data: res} = await this.axios.delete(`users/${id}`);
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getUserList();
        } catch (e) {
          this.$message.error("服务器出错请联系管理员")
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //展示设置角色对话框
    async showSetRoleDialog(row) {
      this.userInfo = row;
      this.setRoleVisible = true;
      try {
        const {data: res} = await this.axios.get('roles');
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }

        this.rolesList=res.data;
      } catch (e) {
        this.$message.error("服务器出错请联系管理员")
      }
    },
    //发送请求后设置角色
    async setRole() {
      if (!this.selectRoleId) {
        return this.$message.warning("请选择角色");
      }
      try {
        const {data: res} = await this.axios.put(`users/${this.userInfo.id}/role`,{rid:this.selectRoleId});
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.getUserList();
        this.setRoleVisible=false
        this.$message.success(res.meta.msg)
      } catch (e) {
        this.$message.error("服务器出错请联系管理员")
      }
    },
    //分配角色对话框的关闭事件
    setRoleClose(){
      this.selectRoleId=''
    }



  }
}
</script>

<style scoped>

.el-table{
  margin-top: 20px;
}
</style>
